#!/usr/bin/env python3
"""
生物信息数据库管理系统 - TUI 界面
使用 Textual 框架实现终端用户界面
"""

from textual.app import App, ComposeResult
from textual.containers import Container, Horizontal, Vertical
from textual.widgets import Header, Footer, Button, Static, DataTable, Label
from textual.binding import Binding
import requests
from datetime import datetime
import sys


class BioInfoTUI(App):
    """生物信息数据库管理 TUI 应用"""
    
    CSS = """
    Screen {
        background: $surface;
    }
    
    #title {
        dock: top;
        height: 3;
        background: $primary;
        color: $text;
        content-align: center middle;
        text-style: bold;
    }
    
    #stats-container {
        height: 5;
        margin: 1;
        border: solid $primary;
    }
    
    .stat-box {
        width: 1fr;
        height: 100%;
        border: round $accent;
        margin: 0 1;
        content-align: center middle;
    }
    
    #buttons-container {
        height: auto;
        margin: 1;
        padding: 1;
    }
    
    Button {
        margin: 1;
        min-width: 20;
    }
    
    #history-container {
        height: 1fr;
        margin: 1;
        border: solid $primary;
    }
    
    DataTable {
        height: 100%;
    }
    
    #status-bar {
        dock: bottom;
        height: 1;
        background: $accent;
        color: $text;
    }
    """
    
    BINDINGS = [
        Binding("q", "quit", "退出"),
        Binding("r", "refresh", "刷新"),
        Binding("h", "show_help", "帮助"),
    ]
    
    def __init__(self):
        super().__init__()
        self.api_base_url = "http://localhost:8000"
        self.stats_data = {}
        self.history_data = []
    
    def compose(self) -> ComposeResult:
        """创建 UI 布局"""
        yield Header()
        
        # 标题
        yield Static("🧬 生物信息数据库管理系统 - TUI", id="title")
        
        # 统计信息容器
        with Horizontal(id="stats-container"):
            yield Static("蛋白质总数: 加载中...", classes="stat-box", id="stat-proteins")
            yield Static("导入次数: 加载中...", classes="stat-box", id="stat-imports")
            yield Static("物种数量: 加载中...", classes="stat-box", id="stat-species")
        
        # 按钮容器
        with Horizontal(id="buttons-container"):
            yield Button("📤 上传提示", id="upload-btn", variant="primary")
            yield Button("📋 查看历史", id="history-btn", variant="success")
            yield Button("🔄 刷新数据", id="refresh-btn")
            yield Button("❌ 退出", id="quit-btn", variant="error")
        
        # 历史记录表格容器
        with Container(id="history-container"):
            yield DataTable(id="history-table")
        
        # 状态栏
        yield Static("就绪 | 按 'h' 查看帮助", id="status-bar")
        yield Footer()
    
    def on_mount(self) -> None:
        """应用挂载时的初始化"""
        # 设置表格列
        table = self.query_one("#history-table", DataTable)
        table.add_columns("ID", "文件名", "导入时间", "行数", "状态")
        
        # 加载初始数据
        self.refresh_all_data()
    
    def on_button_pressed(self, event: Button.Pressed) -> None:
        """处理按钮点击事件"""
        button_id = event.button.id
        
        if button_id == "upload-btn":
            self.action_show_upload_info()
        elif button_id == "history-btn":
            self.action_refresh_history()
        elif button_id == "refresh-btn":
            self.action_refresh()
        elif button_id == "quit-btn":
            self.action_quit()
    
    def refresh_all_data(self) -> None:
        """刷新所有数据"""
        self.update_status("正在刷新数据...")
        self.fetch_stats()
        self.fetch_history()
        self.update_status("数据刷新完成")
    
    def fetch_stats(self) -> None:
        """获取统计信息"""
        try:
            response = requests.get(f"{self.api_base_url}/stats/", timeout=5)
            if response.status_code == 200:
                self.stats_data = response.data
                self.update_stats_display()
            else:
                self.update_status(f"获取统计信息失败: HTTP {response.status_code}")
        except requests.exceptions.ConnectionError:
            self.update_status("错误: 无法连接到后端 API (http://localhost:8000)")
            self.query_one("#stat-proteins", Static).update("蛋白质总数: API 未连接")
            self.query_one("#stat-imports", Static).update("导入次数: API 未连接")
            self.query_one("#stat-species", Static).update("物种数量: API 未连接")
        except Exception as e:
            self.update_status(f"获取统计信息出错: {str(e)}")
    
    def fetch_history(self) -> None:
        """获取导入历史"""
        try:
            response = requests.get(f"{self.api_base_url}/history/", timeout=5)
            if response.status_code == 200:
                self.history_data = response.json()
                self.update_history_table()
            else:
                self.update_status(f"获取历史记录失败: HTTP {response.status_code}")
        except requests.exceptions.ConnectionError:
            self.update_status("错误: 无法连接到后端 API")
        except Exception as e:
            self.update_status(f"获取历史记录出错: {str(e)}")
    
    def update_stats_display(self) -> None:
        """更新统计信息显示"""
        if self.stats_data:
            self.query_one("#stat-proteins", Static).update(
                f"🧬 蛋白质总数: {self.stats_data.get('protein_count', 0)}"
            )
            self.query_one("#stat-imports", Static).update(
                f"📥 导入次数: {self.stats_data.get('import_count', 0)}"
            )
            self.query_one("#stat-species", Static).update(
                f"🔬 物种数量: {self.stats_data.get('species_count', 0)}"
            )
    
    def update_history_table(self) -> None:
        """更新历史记录表格"""
        table = self.query_one("#history-table", DataTable)
        table.clear()
        
        for record in self.history_data[:20]:  # 只显示最近20条
            table.add_row(
                str(record.get('id', '')),
                record.get('file_name', ''),
                self.format_time(record.get('import_time', '')),
                str(record.get('row_count', 0)),
                '✓ 成功' if record.get('status') == 'success' else '✗ 失败'
            )
    
    def format_time(self, time_str: str) -> str:
        """格式化时间字符串"""
        try:
            dt = datetime.fromisoformat(time_str.replace('Z', '+00:00'))
            return dt.strftime('%Y-%m-%d %H:%M')
        except:
            return time_str[:16] if len(time_str) > 16 else time_str
    
    def update_status(self, message: str) -> None:
        """更新状态栏"""
        status_bar = self.query_one("#status-bar", Static)
        status_bar.update(f"{message} | 按 'h' 查看帮助")
    
    def action_show_upload_info(self) -> None:
        """显示上传提示信息"""
        self.update_status("提示: 请使用 Web 界面上传 CSV 文件 (http://localhost:3000/upload)")
        self.notify("请使用 Web 界面上传文件\nURL: http://localhost:3000/upload", 
                   title="上传提示", 
                   severity="information")
    
    def action_refresh_history(self) -> None:
        """刷新历史记录"""
        self.fetch_history()
        self.update_status("历史记录已刷新")
    
    def action_refresh(self) -> None:
        """刷新所有数据"""
        self.refresh_all_data()
    
    def action_show_help(self) -> None:
        """显示帮助信息"""
        help_text = """
        快捷键说明:
        - q: 退出程序
        - r: 刷新所有数据
        - h: 显示此帮助信息
        
        功能说明:
        - 上传提示: 提示如何使用 Web 界面上传文件
        - 查看历史: 刷新并查看最近的导入历史
        - 刷新数据: 刷新统计信息和历史记录
        - 退出: 关闭应用程序
        """
        self.notify(help_text, title="帮助信息", severity="information")
    
    def action_quit(self) -> None:
        """退出应用"""
        self.exit()


def main():
    """主函数"""
    try:
        app = BioInfoTUI()
        app.run()
    except KeyboardInterrupt:
        print("\n程序已退出")
        sys.exit(0)
    except Exception as e:
        print(f"错误: {e}")
        sys.exit(1)


if __name__ == "__main__":
    main()


